package com.jackfangqi.zhihuijizhou.utils;

import java.io.*;
import java.net.HttpURLConnection;

/**
 * Created by gggcccwww on 2015/6/10.
 */
public class StreamUtil {

    public StreamUtil() {
    }

    public static void close(Object stream){
        try {
            if (stream != null) {
                if(stream instanceof InputStream){
                    ((InputStream)stream).close();
                }
                else if(stream instanceof OutputStream){
                    ((OutputStream)stream).close();
                }
                else if(stream instanceof Reader){
                    ((Reader)stream).close();
                }
                else if(stream instanceof Writer){
                    ((Writer)stream).close();
                }
                else if(stream instanceof HttpURLConnection){
                    ((HttpURLConnection)stream).disconnect();
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 读取输入流返回数据
     *
     * @param inputStream
     * @return
     */
    public static byte[] readStream(InputStream inputStream) throws IOException {
//        byte[] ret = null;
//        ByteArrayOutputStream baos = null;
//        byte[] buf = new byte[128];
//        baos = new ByteArrayOutputStream();
//        int len = 0;
//        while (true) {
//            len = inputStream.read(buf);
//            if (len == -1) {
//                break;
//            }
//            baos.write(buf, 0, len);
//        }
//        buf = null;
//        ret = baos.toByteArray();
//        baos.close();
//        return ret;

        byte[] ret=null;
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        long len = readStream(inputStream, baos);
        if(len>0){

            ret=baos.toByteArray();
        }
        close(baos);
        return ret;
    }


    public static long readStream(InputStream in,OutputStream out) throws IOException{
        long ret=0;
        if(in!=null && out!=null){
            byte[] buf=new byte[128];
            int len;
            while (true) {
                len = in.read(buf);
                if (len == -1) {
                    break;
                }
                out.write(buf, 0, len);
                ret+=len;
            }
        }
        return ret;


    }
}
